#include "fishInteractorWidget.h"
#include "fishLight.h"

fishInteractorWidget::fishInteractorWidget(QWidget *parent)
    : QWidget(parent)
{
    ui.setupUi(this);
    pos = 50;
    indicator = 0;
    states[0] =  RENDER_STATE_COLOR ;
    states[1] =  RENDER_STATE_WIREFRAME ;
    moveflag = false;
}

fishInteractorWidget::~fishInteractorWidget()
{
}

void fishInteractorWidget::mousePressEvent(QMouseEvent *event)
{
    lastPos = event->pos();
    moveflag = true;
}

void fishInteractorWidget::keyPressEvent(QKeyEvent *event)
{
    if (event->key() == Qt::Key_Left)
    {
        RotateY(-5);
    }

    else if (event->key() == Qt::Key_Right)
    {
        RotateY(5);
    }

    else if (event->key() == Qt::Key_Up)
    {
        ui.sliceshow->m_device->camera->slide(0,0,10);

    }

    else if (event->key() == Qt::Key_Down)
    {
        ui.sliceshow->m_device->camera->slide(0, 0, -10);
    }
    else if (event->key() == Qt::Key_W)
    {
        if (++indicator >= 2) indicator = 0;
        ui.sliceshow->m_device->SetRenderstate(states[indicator]);
    }
    else return;
}

void fishInteractorWidget::mouseMoveEvent(QMouseEvent *event)
{
    int dx = event->x() - lastPos.x();
    int dy = event->y() - lastPos.y();

    //qDebug() <<"dx:" <<dx;
    //qDebug() << "dy:" << dy;
    switch (event->buttons())
    {
    case Qt::LeftButton:
    {
        if (moveflag)
        {
            RotateY(dx);
            RotateZ(dy);
        }

        break;
    }

    case Qt::RightButton:
        if (moveflag)
        {
            ui.sliceshow->m_device->camera->slide(0, 0, dx);
        }
        break;
    }
    lastPos = event->pos();
    //if (DataSource::GetDataSource()->ifVessel3dcaled==true)
    {
        //Light::addlight();
    }


}

void fishInteractorWidget::mouseReleaseEvent(QMouseEvent *event)
{
    moveflag = false;
}

void fishInteractorWidget::RotateY(float angle)
{
    //ԭʼ
    //qDebug() <<"*********angle:***********" << angle;
    float d = ui.sliceshow->m_device->camera->getDist();
    //float d = ui.sliceshow->camera->getDist();
    int cnt = 48;
    float theta = angle / cnt;
    float slide_d = -2 * d*sin(theta*PI / 360);
    ui.sliceshow->m_device->camera->yaw(-theta / 2);

    //qDebug() <<"*********theta:***********" <<theta;
    for (; cnt != 0; --cnt)
    {
        ui.sliceshow->m_device->camera->slide(slide_d, 0, 0);
        ui.sliceshow->m_device->camera->yaw(-theta );
    }
    ui.sliceshow->m_device->camera->yaw(theta / 2 );
}

void fishInteractorWidget::RotateZ(float angle)
{
    float d = ui.sliceshow->m_device->camera->getDist();
    int cnt = 48;
    float theta = angle / cnt;
    float slide_d = 2 * d*sin(theta*PI / 360);
    ui.sliceshow->m_device->camera->pitch(-theta / 2);
    for (; cnt != 0; --cnt)
    {
        ui.sliceshow->m_device->camera->slide(0, slide_d, 0);
        ui.sliceshow->m_device->camera->pitch(-theta);
    }
    ui.sliceshow->m_device->camera->pitch(theta / 2);
}
